<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="never">
      <!-- 面包屑导航 -->
      <div slot="header" class="clearfix" v-if="$route.query.name">
        <el-breadcrumb   separator-class="el-icon-arrow-right">
          <el-breadcrumb-item>学科管理</el-breadcrumb-item>
          <el-breadcrumb-item>{{$route.query.name}}</el-breadcrumb-item>
          <el-breadcrumb-item>标签管理</el-breadcrumb-item>
          <el-breadcrumb-item></el-breadcrumb-item>
        </el-breadcrumb>
      </div>

      <!-- 目标名称、状态搜索框 -->

      <el-form :inline="true" class="demo-form-inline">
        <el-row type="flex" justify="space-between" align="middle" style="line-height:40px">
          <el-col>
            <el-form-item label="标签名称">
              <el-input v-model="tagForm.tagName"></el-input>
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="tagForm.state" placeholder="请选择">
                 <el-option
                      v-for="item in status"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button @click="clear">清除</el-button>
              <el-button type="primary" @click="search">搜索</el-button>
            </el-form-item>
          </el-col>

          <el-col  :span="5" >
            <router-link class="returnSubject" to="/subjects/list" v-if="$route.query.id">
                <i class="el-icon-back"></i>返回学科</router-link>
            <el-form-item>
              <el-button style="background:#67c23a; color:#fff" icon="el-icon-edit" @click="openDialog('add',$event)">新增标签</el-button>
          </el-form-item>
          </el-col>
        </el-row>
      </el-form>

        <!-- 警告栏 -->
        <el-alert
        :title="cResultTip"
          type="info"
          class="alert"
          :closable="false"
          show-icon
        ></el-alert>

        <!-- 表格 -->
        <el-table :data="tableData" style="width: 100%" v-loading="isLoading" >
          <el-table-column
            label="序号"
            width="100">
            <template slot-scope="{ $index }">
              {{ $index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="subjectName" label="所属学科" width="180">
          </el-table-column>
          <el-table-column prop="tagName" label="标签名称">
          </el-table-column>
          <el-table-column prop="username" label="创建者">
          </el-table-column>
          <el-table-column prop="addDate" label="创建日期"  :formatter="repaced">
          </el-table-column>
          <el-table-column label="状态" prop="state" :formatter="formatState">
            <template slot-scope="data">
              <span v-if="data.row.state==1">已启用</span>
              <span v-else>禁用</span>
            </template>
          </el-table-column>
          <!-- 操作 -->
          <el-table-column prop="" label="操作">
            <template slot-scope="{row}">
              <el-button type="text" @click="Disable(row)">
                  <span v-if="row.state === 0">启用</span>
                  <span v-else>禁用</span>
              </el-button>
              <el-button type="text" :disabled="row.state =='0'" @click="openDialog('edit',row)">修改</el-button>
              <el-button type="text" :disabled="row.state == '0'" @click="del(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
         <div class="block">

          <!-- 分页器 -->
          <el-pagination
            background
            :current-page="tagForm.page"
            :total="total"
            @size-change="hSizeChange"
            @current-change='handleCorrentChange'
            :page-sizes="[5, 10, 20,50]"
            :page-size="10"
            layout=" prev, pager, next, sizes, jumper"
           >
          </el-pagination>
        </div>
      </el-card>

      <!-- 对话框 -->
      <el-dialog
        :title="title"
        style="font-size:22px"
        :visible.sync="showDialog"
        width="25%"
        @close="close">
        <el-form ref="addForm" label-width="100px" :rules="addFormRules" :model="addForm">
          <el-form-item label="所属学科" prop="subjectID" v-if="!$route.query.id">
            <el-select style="width:100%" v-model="addForm.subjectID" @change="handleSelectChange">
               <el-option
                v-for="item in subjectList"
                :key="item.id"
                :label="item.subjectName"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="标签名称" prop="tagName">
            <el-input placeholder="请输入标签名称" v-model="addForm.tagName"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button @click="close">取消</el-button>
            <el-button type="primary" @click="btnOk">确认</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { list, changeState, add, remove, update, detail } from '@/api/hmmm/tags'
import { list as getSubject } from '@/api/hmmm/subjects'
import { status } from '@/api/hmmm/constants'
export default {
  data () {
    return {
      tableData: [], // 获取的标签列表数据
      total: 0, // 总条数,
      searchKeyword: '', // 搜索关键字
      selectedOption: null, // 搜索状态
      showDialog: false, // 展示dialog
      title: '', // 对话框标题
      addForm: {
        subjectID: null, // 学科ID
        tagName: '', // 标签名称,
        id: ''
      },
      tagForm: {
        tags: '',
        state: '',
        page: 1, // 当前页码
        pagesize: 10, // 一页多少条
        tagName: ''
      },
      addFormRules: {
        tagName: [
          { required: true, message: '请输入目录名称', trigger: 'blur' }
        ],
        subjectID: [
          { required: true, message: '请输入所属学科', trigger: 'blur' }
        ]
      },
      subjectList: [], // 获取学科列表
      type: 'add', // 添加编辑点击按钮类型
      isLoading: false
    }
  },
  created () {
    // 标签列表数据
    this.getTagsList()
    this.getSubjectList()
    // console.log()
  },
  computed: {
    cResultTip () {
      return `数据一共 ${this.total} 条`
    },
    status () {
      return status
    }

  },
  methods: {
    // 查询
    buildParams () {
      const paramsObj = {}
      const { page, pagesize, tagName, state } = this.tagForm
      paramsObj.page = page || null
      paramsObj.pagesize = pagesize || null
      paramsObj.tagName = tagName || null
      paramsObj.state = state === '' ? null : state
      return paramsObj
    },
    // 获取标签列表数据，进行渲染
    async getTagsList () {
      // 构建查询参数
      const paramsObj = this.buildParams()
      if (this.$route.query.id) {
        this.addForm.subjectID = this.$route.query.id
        const { data } = await list(this.addForm)
        this.tableData = data.items
        this.total = data.counts
        // console.log(res);
        this.isLoading = false
      } else {
        try {
          const { data } = await list(paramsObj)
          // console.log(data)
          this.tableData = data.items
          this.total = data.counts
          // console.log(res);
          this.isLoading = false
        } catch (err) {
          // console.log(err)
          this.isLoading = true
        }
      }
    },
    handleCorrentChange (value) {
      // console.log(value)
      this.tagForm.page = value
      this.getTagsList()
    },
    // 更换一页显示多少条
    hSizeChange (value) {
      // console.log(value)
      this.tagForm.pagesize = value
      if (this.tagForm.page === 1) {
        this.getTagsList()
      }
    },
    // 枚举
    formatState (row, column, cellValue, index) {
      // console.log(cellValue)
      const obj = list.find(item => {
        return item.value === cellValue
      })
      return obj
    },
    // 点击禁用
    async Disable (row) {
      row.state = row.state ? 0 : 1
      this.tableData.forEach(item => {
        if (item.id === row.id) {
          item.state = row.state
        }
      })
      await changeState(row)
    },
    // 打开弹框
    async openDialog (type, row) {
      this.type = type
      // console.log(type, row.id)
      if (type === 'add') {
        this.title = '新增标签'
        this.showDialog = true
      }
      if (type === 'edit') {
        this.title = '修改标签'
        this.showDialog = true
        const res = await detail(row)
        this.addForm.id = row.id
        if (this.addForm.id) {
          this.addForm = res.data
        }
      }
    },
    // 获取学科列表渲染
    async getSubjectList () {
      const res = await getSubject()
      // console.log(res)
      this.subjectList = res.data.items
    },
    // 页码
    handleSelectChange (value) {
      this.addForm.subjectID = value
      console.log(this.addForm.subjectID)
    },
    // 对话框确认按钮
    btnOk () {
      // 增加标签
      this.$refs.addForm.validate(async (valid) => {
        if (valid) {
          // 判断是否有id,有就是编辑，没有就是新增
          if (this.addForm.id) {
            await update(this.addForm)

            this.getTagsList()
            this.close()
            this.$message.success('修改标签成功')
          } else {
            if (this.$route.query.id) {
              this.addForm.subjectID = Number(this.$route.query.id)
              await add(this.addForm)
              this.page = 1
              this.getTagsList()
              this.close()
              this.$message.success('新增标签成功')
            } else {
              await add(this.addForm)
              this.page = 1
              this.getTagsList()
              this.close()
              this.$message.success('新增标签成功')
            }
          }
        } else {
          return false
        }
      })
    },
    // 关闭按钮
    close () {
      this.$refs.addForm.resetFields()
      this.showDialog = false
    },
    // 删除
    async del (row) {
      // console.log(id)
      this.$confirm('此操作将永久删除该学科, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await remove(row)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        this.getTagsList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 搜索
    search () {
      if (!this.tagForm) return
      // 重置页码
      this.tagForm.page = 1
      // 重发请求
      this.getTagsList()
    },
    // 清空表单
    clear () {
      this.tagForm.tagName = '' // 搜索关键字
      this.tagForm.state = null // 搜索状态
      this.getTagsList()
    },
    repaced (row, column, cellValue, index) {
      return cellValue.replace('T', ' ').substring(0, 19)
    }

  }
}
</script>

<style scoped>
.block {
  margin-top: 20px;
  text-align: right;
}
.returnSubject {
  margin-right: 10px;
  font-size: 14px;
  color:#409eff
}
</style>
